
import axios from 'axios';
import { ElMessage } from 'element-plus'
import {Tool} from "@/utils/tool";
const service = axios.create({
    baseURL:import.meta.env.VITE_BASE_URL,
    timeout: 5000
});

service.interceptors.request.use(
    (config:any) => {
        let token = Tool.getInstance().getLoginUser().token;
        if (Tool.getInstance().isNotEmpty(token)) {
            config.headers['Authorization'] = `Bearer ${token}`;
        }
        return config;
    },
    (error:any) => {
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(

    (response:any )=> {
        if (response.status == 200) {
            if(response.headers['content-disposition']!=undefined&&response.headers['content-disposition'].indexOf("filename")!=-1){//如果是文件下载
               return response;
            }
            return response.data;
        } else {
            if (document.getElementsByClassName('el-message').length === 0) {//每次只弹一次
                ElMessage.error(response.msg);
            }
            return Promise.reject(response);
        }
    },
    (error:any) => {
        if (document.getElementsByClassName('el-message').length === 0) {//每次只弹一次
            debugger
            if(error.response!=undefined) {
                if(error.response.status==401){
                    ElMessage.error("暂无权限")
                    Tool.getInstance().removeLoginUser();
                    window.location.href = '/';
                }else {
                    let data=error.response.data
                    if(typeof data ==="string" && data!='')
                       ElMessage.error(error.response.data);
                    else
                        ElMessage.error(error.message);
                }
            }else{
                
                ElMessage.error(error.message)
            }

        }
        return Promise.reject(error)

    }
);

export default service;
